package com.jimo.flutter_frpc

import android.app.Activity
import frpclib.Frpclib

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File
import java.io.FileWriter

class FlutterFrpcPlugin: FlutterPlugin, MethodCallHandler ,ActivityAware{
  private lateinit var activity: Activity
  private lateinit var channel : MethodChannel
  override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_frpc")
    channel.setMethodCallHandler(this)
  }

  override fun onMethodCall(call: MethodCall, result: Result) {
    when (call.method) {
        "init" -> {
          val aa=call.arguments as Map<*, *>
          updateInit(aa["content"]!! as String)
          result.success("")
        }
        "connect" -> {
          Thread {
            val file = File(activity.filesDir, "frpc.ini")
            if (file.exists()) {
              val savePath: String = file.absolutePath
              Frpclib.run(savePath)
            }
          }.start()
          result.success("")
        }
        "disconnect" -> {
          Frpclib.stop()
          result.success("")
        }
        else -> {
          result.notImplemented()
        }
    }
  }

  override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }
  private fun updateInit(s: String) {
    try {
      val file = File(activity.filesDir, "frpc.ini")
      val fileWriter = FileWriter(file)
      fileWriter.write(s)
      fileWriter.close()
    } catch (e: Exception) {
      e.printStackTrace()
    }
  }

  override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity=binding.activity
  }

  override fun onDetachedFromActivityForConfigChanges() {
  }

  override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
  }

  override fun onDetachedFromActivity() {
  }
}
